package com.cs2.volunteerpostbackend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs2.volunteerpostbackend.dao.MomentMapper;
import com.cs2.volunteerpostbackend.dao.UserMapper;
import com.cs2.volunteerpostbackend.po.Moment;
import com.cs2.volunteerpostbackend.po.User;
import com.cs2.volunteerpostbackend.service.MomentService;
import com.cs2.volunteerpostbackend.web.dto.moment.MomentUserVO;
import com.cs2.volunteerpostbackend.web.dto.moment.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

@Service
public class MomentServiceImpl extends ServiceImpl<MomentMapper, Moment> implements MomentService {

    @Autowired
    private MomentMapper momentMapper;

    @Override
    public IPage<MomentUserVO> listMomentsWithUserInfo(int page, int size, String userId, int type) {
        System.out.println(">>> 执行查询动态列表 (页码:" + page + ", 大小:" + size + ", 用户ID:" + userId + ", 类型:" + type + ")");
        try {
            // 创建分页对象，page从1开始
            Page<MomentUserVO> pagination = new Page<>(page, size);
            
            // 使用MyBatis关联查询优化性能
            IPage<MomentUserVO> result = momentMapper.selectMomentsWithUserInfo(pagination, userId, type);
            
            // 获取动态ID列表
            List<String> momentIds = result.getRecords().stream()
                    .map(MomentUserVO::getId)
                    .collect(Collectors.toList());
            
            // 查询图片信息
            if (!momentIds.isEmpty()) {
                List<ImageVO> imageList = momentMapper.selectImagesByMomentIds(momentIds);
                
                // 将图片信息按动态ID分组
                Map<String, List<ImageVO>> imageMap = new HashMap<>();
                for (ImageVO image : imageList) {
                    String momentId = image.getMomentId();
                    imageMap.computeIfAbsent(momentId, k -> new ArrayList<>()).add(image);
                }
                
                // 将图片信息关联到动态
                for (MomentUserVO momentUserVO : result.getRecords()) {
                    // 从map中获取该动态的图片列表
                    List<ImageVO> images = imageMap.getOrDefault(momentUserVO.getId(), new ArrayList<>());
                    // 移除momentId字段，避免暴露给前端
                    images.forEach(image -> image.setMomentId(null));
                    momentUserVO.setImages(images);
                }
            }
            
            System.out.println("<<< 查询完成，共 " + result.getTotal() + " 条记录");
            return result;
        } catch (Exception e) {
            System.err.println("!!! 查询动态列表失败: " + e.getMessage());
            throw e; // 抛出异常让控制器处理
        }
    }

    @Override
    public Moment createMoment(Moment moment) {
        System.out.println(">>> 执行创建动态 (标题:" + moment.getTitle() + ")");
        try {
            // 1. 初始化点赞数为0（覆盖前端可能传递的值，确保初始值正确）
            moment.setLikeCount(0);

            // 2. 保留前端传递的updateTime（如果传递了则使用，否则用当前时间）
            if (moment.getUpdateTime() == null) {
                moment.setUpdateTime(System.currentTimeMillis());
            }

            // 3. 执行插入操作（前端传递的title、content、posterId、status将被保留）
            // MyBatis-Plus会自动生成ID，无需手动设置
            momentMapper.insert(moment);
            System.out.println("<<< 动态创建成功，ID: " + moment.getId());
            return moment;
        } catch (Exception e) {
            System.err.println("!!! 创建动态失败: " + e.getMessage());
            throw e;
        }
    }

    @Override
    public Moment updateMoment(Moment moment) {
        System.out.println(">>> 执行更新动态 (ID:" + moment.getId() + ")");
        try {
            if (Objects.isNull(moment.getId())) {
                throw new IllegalArgumentException("动态ID不能为空");
            }
            moment.setUpdateTime(System.currentTimeMillis()); // 更新时间戳
            momentMapper.updateById(moment);
            Moment updatedMoment = momentMapper.selectById(moment.getId());
            System.out.println("<<< 动态更新成功");
            return updatedMoment;
        } catch (IllegalArgumentException e) {
            System.err.println("!!! 更新动态参数错误: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.err.println("!!! 更新动态失败: " + e.getMessage());
            throw e;
        }
    }

    @Override
    public Moment increaseLikeCount(String id) {
        System.out.println(">>> 执行点赞操作 (ID:" + id + ")");
        try {
            if (id == null || id.trim().isEmpty()) {
                throw new IllegalArgumentException("动态ID不能为空");
            }

            // 查询动态
            Moment moment = momentMapper.selectById(id);
            if (moment == null) {
                throw new RuntimeException("找不到指定ID的动态");
            }

            // 增加点赞数
            moment.setLikeCount(moment.getLikeCount() + 1);
            momentMapper.updateById(moment);

            System.out.println("<<< 点赞成功，当前点赞数: " + moment.getLikeCount());
            return moment;
        } catch (IllegalArgumentException e) {
            System.err.println("!!! 点赞参数错误: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.err.println("!!! 点赞失败: " + e.getMessage());
            throw e;
        }
    }

    @Override
    public int deleteMoment(String id) {
        System.out.println(">>> 执行删除动态 (ID:" + id + ")");
        try {
            if (id == null || id.trim().isEmpty()) {
                throw new IllegalArgumentException("动态ID不能为空");
            }

            int deletedRows = momentMapper.deleteById(id);
            if (deletedRows == 0) {
                throw new RuntimeException("找不到指定ID的动态");
            }

            System.out.println("<<< 动态删除成功");
            return deletedRows;
        } catch (IllegalArgumentException e) {
            System.err.println("!!! 删除参数错误: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.err.println("!!! 删除动态失败: " + e.getMessage());
            throw e;
        }
    }
}